//
//  KZIndexProgressView.m
//  听说弱点强化训练
//
//  Created by 朱凯 on 2018/10/22.
//  Copyright © 2018年 盛超. All rights reserved.
//

#import "KZIndexProgressView.h"

@implementation KZIndexProgressView
{
    UIImageView *_progressBgView;
    UIImageView *_progressView;
    CAShapeLayer *_progressLayer;
    
    UILabel *_indexLabel;
}

- (instancetype)init {
    
    if (self = [super init]) {
        
        _totalIndex = 0;
        _index = 0;
        [self setupUI];
    }
    return self;
}

- (void)setupUI {
    
    _indexLabel = [[UILabel alloc] init];
    _indexLabel.adjustsFontSizeToFitWidth = true;
    _indexLabel.numberOfLines = 1;
    _indexLabel.text = @"0/0";
    _indexLabel.font = FONT(12);
    _indexLabel.textAlignment = NSTextAlignmentRight;
    _indexLabel.textColor = [UIColor lightGrayColor];
    [self addSubview:_indexLabel];
    [_indexLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(W(-10));
        make.centerY.equalTo(self);
        make.width.mas_equalTo(W(40));
    }];
    
    _progressBgView = [UIImageView new];
    _progressBgView.image = [UIImage imageNamed:@"kz-进度底纹条"];
    [self addSubview:_progressBgView];
    [_progressBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(W(10));
        make.right.equalTo(_indexLabel.mas_left).offset(W(-5));
        make.centerY.equalTo(self);
        make.height.mas_equalTo(H(8));
    }];
    
    _progressView = [UIImageView new];
    _progressView.image = [UIImage imageNamed:@"kz-进度完整条"];
    [self addSubview:_progressView];
    [_progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(_progressBgView);
    }];
   
    _progressLayer = [CAShapeLayer layer];
    _progressLayer.lineWidth = H(8);
    _progressLayer.strokeStart = 0;
    _progressLayer.lineCap = kCALineCapRound;
    _progressLayer.strokeColor = UIColor.whiteColor.CGColor;
    _progressLayer.fillColor = UIColor.clearColor.CGColor;
    _progressView.layer.mask = _progressLayer;
}
- (void)layoutSubviews {
    
    [super layoutSubviews];
    
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake(0, _progressView.height / 2)];
    [path addLineToPoint:CGPointMake(_progressView.width, _progressView.height / 2)];
    _progressLayer.path = path.CGPath;
}

- (void)setIndex:(NSInteger)index {
    
    _index = index;

    _progressLayer.strokeEnd = _index * 1.0 / _totalIndex;
    
    NSString *text = [NSString stringWithFormat:@"%li/%li", _index, _totalIndex];
    NSString *indexTexgt = [NSString stringWithFormat:@"%li", _index];
    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:text];
    [attr addAttribute:NSForegroundColorAttributeName value:KZThemeColor range:[text rangeOfString:indexTexgt]];
    [attr addAttribute:NSFontAttributeName value:FONT(16) range:[text rangeOfString:indexTexgt]];
    _indexLabel.attributedText = attr.copy;

}

@end
